# -*- coding: utf-8 -*-
"""
Created on Thu Nov  1 22:15:50 2018

@author: Administrator
"""

class LNode:
    
    def __init__(self, element, next_ = None):
        self.element = element
        self.next = next_
        
#print(LNode(5).element)
        
class ArgumentsMistakeError(ValueError):
    pass

class LinkedCircleList:
    """This is an implemention of linked circle list
    """
    def __init__(self):
        self.rear = None
        self.length = 0
        
    def is_empty(self):
        if self.rear is None:
            return True
        return False
    
    def length_list(self):
        return self.length
    
    def prepend(self, element):
        """ insert an element at the begining of the linked list
        """
        # if no element
        node = LNode(element)
        if self.rear is None:
            node.next = node
            self.rear = node
        # if elements exist (consider two elements situation)
        # new created node link to the first node of the list
        else:
            node.next = self.rear.next
            self.rear.next = node
            
        self.length += 1
    
    def append(self, element):
        """insert element at the end of the linked list
        """
        # if no element exist
        node = LNode(element)
        if self.rear is None:
            node.next = node
            self.rear = node
        else: 
            # if element exist
            node.next = self.rear.next
            self.rear.next = node
            self.rear = node
        self.length += 1
    
    def delete_first(self):
        """delete the first node of the linked list
        """
        # if no element
        if self.rear is None:
            raise ValueError("linked circle list empty")
        # if one element
        elif self.rear.next == self.rear:
            self.rear = None
        else: # more element
            self.rear.next = self.rear.next.next
        self.length -= 1
    
    def delete_last(self):
        
        # if no element
        if self.rear is None:
            raise ValueError("linked circle list empty")
        elif self.rear.next == self.rear:
            self.rear = None
        else:
            head = p = self.rear.next
            while p.next != self.rear:
                p = p.next
            if p.next == self.rear: # find the before last one
                self.rear = p
                p.next = head
            self.length -= 1
    
    def print_all(self):
        result = []
        if self.rear is None:
            return result
        p = self.rear.next
        while True:
            result.append(p.element)
            if p == self.rear:
                break
            p = p.next
        return result
                
            
